#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <memory>
#include "Socket.hpp"
#include "Log.hpp"
#include <sys/epoll.h>

using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;

#define MAX 4096

// 最开始的时候，tcpserver 只有一个socketfd
class EpollServer
{
    static const int revs_num = 64;
public:
    EpollServer(int port)
        : _port(port), 
        _epfd(gdefaultfd),
        _listen_socket(std::make_unique<TcpSocket>()),
        _isrunning(false)
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 1. 创建epoll模型
        _epfd = epoll_create(256);
        if(_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::DEBUG) << "epoll_create success: " << _epfd; 

        // 2. 至少要将listensock 添加到epoll模型中
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &ev);
        if(n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }

    void Loop()
    {
        int timeout = 1000;
        _isrunning = true;

        while (_isrunning)
        {
            // 我们不能让 accept 来阻塞检测新连接到来，而因该让 select 来负责进行 就绪事件的检测
            // 用户告诉内核，你要帮我关心 &rfds，该事件啊！！
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);   
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("epoll_wait");
                break;
            default:
                // 有事件就绪了
                //  内核告诉用户，你关心的 有哪些已经就绪了!!!
                Dispatcher(n);    // 把已经就绪的 sockfd 派发给指定的模块
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter() // 回调函数
    {
        InetAddr client;
        // listensockfd 就绪了！ 获取新连接不就好了吗？
        int newfd = _listen_socket->Accepter(&client); //  此时一定不会被阻塞 select 告诉我 listensockfd 已经就绪了！ 只执行 “拷贝”
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新的连接： " << newfd << " client info " << client.Addr() << std::endl;

            // 我们需要将新的 newfd添加给epoll，让epoll帮我们进行监管
            struct epoll_event ev;
            ev.data.fd = newfd;
            ev.events = EPOLLIN;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                close(newfd);
                return ;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << newfd;
        }
    }

    void Recver(int who)    // 回调函数
    {
        // 合法的就绪的普通的 fd
        char buffer[1024];
        ssize_t n = recv(who, buffer, sizeof(buffer) - 1, 0); // 此时也不会被阻塞 就绪
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // 把读到的信息， 再回显回去
            std::string message = "echo# ";
            message += buffer;
            send(who, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出， sockfd: " << who;
            // 把fd从epoll中移除, 必须保证fd是一个合法的fd
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, who, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl_del error";
                return ;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl_del success: " << who;
            close(who); // 坑
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错， sockfd: " << who;
            // 把fd从epoll中移除
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, who, nullptr);
            if(m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl_del error";
                return ;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl_del success: " << who;
            close(who); // 坑
        }
    }

    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int events = _revs[i].events;
            int fd = _revs[i].data.fd;
            if(fd == _listen_socket->Fd())
            {
                if(events & EPOLLIN)
                {
                    // listen sock fd 就绪
                    Accepter();
                }
            }
            else 
            {
                // 普通文件描述符就绪
                if(events & EPOLLIN)
                {
                    // 读事件就绪
                    Recver(fd);
                }
                // else if(events & EPOLLOUT)
                // {
                //     // 写事件就绪
                // }
            }
        }
    }

    std::string Evects2Str(short events)
    {
        std::string s = (events & EPOLLIN) ? "POLLIN" : "";
        s +=  (events & EPOLLOUT) ? "POLLOUT" : "";
        return s;
    }

    ~EpollServer()
    {
        _listen_socket->Close();
        if(_epfd >= 0) close(_epfd);
    }

private:
    uint16_t _port;
    int _epfd;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct epoll_event _revs[revs_num];
};